package com.groupseven.backend.controller;

import com.groupseven.backend.domain.Program.Manager;
import com.groupseven.backend.domain.Program.Program;
import com.groupseven.backend.domain.Program.ProgramApplication;
import com.groupseven.backend.domain.Program.TeamMember;
import com.groupseven.backend.domain.ResultType;
import com.groupseven.backend.services.ProgramService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/application")
public class ProgramApplicationController {
    @Autowired
    private ProgramService programService;

    /**
     * 查看自己申报的项目------教师功能
     * @Author 王志华
     * @param Username
     * @return
     */
    @GetMapping("/{Username}")
    public ResultType getMyApplications(@PathVariable String Username){
        return null;
    }

    /**
     * 查看所有申报的项目------管理员功能
     * @Author 王志华
     * @return
     */
    @GetMapping("/all")
    public ResultType getApplications(){
        List<ProgramApplication> applications = programService.findAllProgamApplicationInfo();
        ResultType result = new ResultType(1,"成功",200);
        applications = programService.setManagerAndTeamMembers(applications);
        result.setApplications(applications);
        return result;
    }

    @GetMapping("/unreviewed")
    public ResultType getUnreviewed(){
        List<ProgramApplication> applications = programService.findUnreviewed();
        ResultType result = new ResultType(1,"成功",200);
        applications = programService.setManagerAndTeamMembers(applications);
        result.setApplications(applications);
        return result;
    }

    @GetMapping("/reviewed")
    public ResultType getReviewed(){
        List<ProgramApplication> applications = programService.findReviewed();
        ResultType result = new ResultType(1,"成功",200);
        applications = programService.setManagerAndTeamMembers(applications);
        result.setApplications(applications);
        return result;
    }

    @PostMapping("/")
    public ResultType addProgramApplication(@RequestBody Program application){
        if(programService.insertProgramInfo(application)>0){
            return new ResultType(1,"新增项目申报【"+application.getProgramname()+"】成功",200);
        }
        return new ResultType(0,"新增项目申报【"+application.getProgramname()+"】失败",200);
    }

    /**
     * 项目申报
     * @Author 王志华
     * @param form
     * @return
     */
//    @RequiresPermissions("operate_programs_applications")
    @PostMapping("")
    public ResultType addApplication(@RequestBody ProgramApplication form){
        String number = UUID.randomUUID().toString();
        form.setApprovalStatus(2);
        boolean flag = true;
        Manager manager = new Manager();
        manager.setProgramNumber(form.getProgramNumber());
        manager.setAffiliation(form.getManagerUnit());
        manager.setEmail(form.getManagerEmail());
        manager.setPhone(form.getManagerPhone());
        manager.setName(form.getManagerName());
        List<TeamMember> members = form.getTeamMembers();
        /////////////////////////////////////////////
        Date date=new Date();
        form.setStartTime(date);
        /////////////////////////////////////////////
        form.setManager(null);
        form.setTeamMembers(null);
        form.setProgramNumber(number);
        if(programService.insertProgramApplication(form)==0){
            flag = false;
            return new ResultType(0,"插入失败",200);
        }
        /**
         * 插入负责人
         */
        manager.setProgramNumber(form.getProgramNumber());
        if (programService.insertManagerForApplication(manager)==0){
            flag = false;
            return new ResultType(0,"插入失败",200);
        }
        /**
         * 插入团队成员
         */
        for(TeamMember i : members){
            i.setProgramNumber(form.getProgramNumber());
            if (programService.insertTeamMemberForApplication(i) == 0){
                flag = false;
                return new ResultType(0,"插入失败",200);
            }
        }
        /**
         * 插入完毕进行判断
         */

        if(flag){
            return new ResultType(1,"插入成功",200);
        }
        return new ResultType(0,"插入失败",200);
    }

    @RequiresPermissions("operate_programs_applications")
    @PutMapping("")
    public ResultType updateApplication(@RequestBody @Valid ProgramApplication application) {
        Manager manager = application.getManager();
        List<TeamMember> members = application.getTeamMembers();
        application.setManager(null);
        application.setTeamMembers(null);
        if(programService.findProgramNumberFromProgramApplication(application.ProgramNumber)==null){
            return new ResultType(0,"修改失败",200);
        }
        else {
            manager.setProgramNumber(application.getProgramNumber());
            programService.updateManagerForApplication(manager.ProgramNumber);
            programService.deleteTeamMemberForApplication(application.ProgramNumber);
            for(TeamMember i : members) {
                i.setProgramNumber(application.getProgramNumber());
                programService.insertTeamMemberForApplication(i);
            }
            return new ResultType(1,"修改成功",200);
        }
    }

    @RequiresPermissions("operate_programs_applications")
    @DeleteMapping("{ProgramNumber}")
    public ResultType deleteApplication(@PathVariable String ProgramNumber){
        if(programService.findProgramNumberFromProgramApplication(ProgramNumber)==null){
            return new ResultType(0,"删除失败",200);
        }
        else {
            programService.deleteTeamMemberForApplication(ProgramNumber);
            programService.deleteManagerForApplication(ProgramNumber);
            programService.deleteProgramApplicationByProgramNumber(ProgramNumber);
            return new ResultType(0,"删除成功",200);
        }
    }

    @GetMapping("/firstreview")
    public ResultType getApplicationForFirstReview(){
        List<Program> tmp = programService.selectAllPrograms();
        List<ProgramApplication> apps = programService.findAllProgamApplicationInfo();
        apps = programService.setManagerAndTeamMembers(apps);
        List<Program> target = new ArrayList<>();
        for(ProgramApplication appIterator : apps){
            if(appIterator.getApprovalStatus()==2){
                Program program = new Program();
                program.setProgramname(appIterator.getProgramName());
                program.setApprovalStatus(appIterator.getApprovalStatus());
                program.setAffiliation(appIterator.getAffiliation());
                program.setManager(appIterator.getManager().getName());
                program.setLevel(appIterator.getLevel());
                program.setAmount(appIterator.getReportExpenses());
                program.setDeclarer(appIterator.getDeclarer());
                program.setProgramNumber(appIterator.getProgramNumber());
                target.add(program);
            }
        }
        for(Program programIterator : tmp){
            if(programIterator.getApprovalStatus()==1||programIterator.getApprovalStatus()==3||programIterator.getApprovalStatus()==4){
                continue;
            }
            target.add(programIterator);
        }
        ResultType result = new ResultType(1,"查询初审项目成功",200);
        if(target.size()!=0){
            result.setPrograms(target);
        } else {
            result.setPrograms(target);
            result.setMsg("查询不到符合要求的项目");
        }
        return result;
    }

    @GetMapping("/firstreview/search/{query}")
    public ResultType getApplicationForFirstReviewFuzzySearch(@PathVariable String query){
        List<Program> tmp = programService.selectAllPrograms();
        List<ProgramApplication> apps = programService.findAllProgamApplicationInfo();
        apps = programService.setManagerAndTeamMembers(apps);
        List<Program> target = new ArrayList<>();
        for(ProgramApplication appIterator : apps){
            if(appIterator.getApprovalStatus()==2){
                Program program = new Program();
                program.setProgramname(appIterator.getProgramName());
                program.setApprovalStatus(appIterator.getApprovalStatus());
                program.setAffiliation(appIterator.getAffiliation());
                program.setLevel(appIterator.getLevel());
                program.setManager(appIterator.getManager().getName());
                program.setAmount(appIterator.getReportExpenses());
                program.setDeclarer(appIterator.getDeclarer());
                program.setProgramNumber(appIterator.getProgramNumber());
                target.add(program);
            }
        }
        for(Program programIterator : tmp){
            if(programIterator.getApprovalStatus()==1||programIterator.getApprovalStatus()==3||programIterator.getApprovalStatus()==4){
                continue;
            }
            if(programIterator.getProgramNumber().contains(query)||programIterator.getProgramname().contains(query)||programIterator.getManager().contains(query)){
                target.add(programIterator);
            }
        }
        ResultType result = new ResultType(1,"模糊查询初审项目成功",200);
        if(target.size()!=0){
            result.setPrograms(target);
        } else {
            result.setMsg("查询不到符合要求的项目");
        }
        return result;
    }

    @GetMapping("/secondreview")
    public ResultType getApplicationForSecondReview(){
        List<Program> tmp = programService.selectAllPrograms();
        List<ProgramApplication> apps = programService.findAllProgamApplicationInfo();
        apps = programService.setManagerAndTeamMembers(apps);
        List<Program> target = new ArrayList<>();
        for(ProgramApplication appIterator : apps){
            if(appIterator.getApprovalStatus()==2){
                Program program = new Program();
                program.setProgramname(appIterator.getProgramName());
                program.setApprovalStatus(appIterator.getApprovalStatus());
                program.setAffiliation(appIterator.getAffiliation());
                program.setLevel(appIterator.getLevel());
                program.setManager(appIterator.getManager().getName());
                program.setAmount(appIterator.getReportExpenses());
                program.setDeclarer(appIterator.getDeclarer());
                program.setProgramNumber(appIterator.getProgramNumber());
                target.add(program);
            }
        }
        for(Program programIterator : tmp){
            if(programIterator.getApprovalStatus()==1&&programIterator.getFirstReview().equals("1088")){
                target.add(programIterator);;
            }
        }
        ResultType result = new ResultType(1,"查询二审项目成功",200);
        if(target.size()!=0){
            result.setPrograms(target);
        } else {
            result.setPrograms(target);
            result.setMsg("查询不到符合要求的项目");
        }
        return result;
    }

    @GetMapping("/secondreview/search/{query}")
    public ResultType getApplicationForSecondReviewFuzzySearch(@PathVariable String query){
        List<Program> tmp = programService.selectAllPrograms();
        List<ProgramApplication> apps = programService.findAllProgamApplicationInfo();
        apps = programService.setManagerAndTeamMembers(apps);
        List<Program> target = new ArrayList<>();
        for(ProgramApplication appIterator : apps){
            if(appIterator.getApprovalStatus()==2){
                Program program = new Program();
                program.setProgramname(appIterator.getProgramName());
                program.setApprovalStatus(appIterator.getApprovalStatus());
                program.setAffiliation(appIterator.getAffiliation());
                program.setLevel(appIterator.getLevel());
                program.setManager(appIterator.getManager().getName());
                program.setAmount(appIterator.getReportExpenses());
                program.setDeclarer(appIterator.getDeclarer());
                program.setProgramNumber(appIterator.getProgramNumber());
                target.add(program);
            }
        }
        for(Program programIterator : tmp){
            if(programIterator.getApprovalStatus()==1&&programIterator.getFirstReview().equals("1088")){
                if(programIterator.getProgramNumber().contains(query)||programIterator.getProgramname().contains(query)||programIterator.getManager().contains(query)){
                    target.add(programIterator);
                }
            }
        }
        ResultType result = new ResultType(1,"模糊查询二审项目成功",200);
        if(target.size()!=0){
            result.setPrograms(target);
        } else {
            result.setMsg("查询不到符合要求的项目");
        }
        return result;
    }

    //校级code 1088
    @PutMapping("/passfirstreview")
    public ResultType passfirstReview(@RequestBody Program program){
        programService.insertProgramInfo(program);
        if(program.getApprovalStatus()!=2){
            System.out.println("审核状态是："+program.getApprovalStatus());
            return new ResultType(0,"项目【"+program.getProgramname()+"】不处于未审核状态",200);
        }
        if(programService.passFirstReview(program.getProgramNumber())>0){
            return new ResultType(1,"项目【"+program.getProgramname()+"】初审通过",200);
        }
        return new ResultType(0,"项目【"+program.getProgramname()+"】初审发生错误",200);
    }

    @PutMapping("/denyfirstreview")
    public ResultType denyfirstReview(@RequestBody Program program){
        programService.insertProgramInfo(program);
        if(program.getApprovalStatus()!=2){
            return new ResultType(0,"项目【"+program.getProgramname()+"】不处于未审核状态",200);
        }
        if(programService.denyFirstReview(program.getProgramNumber())>0){
            return new ResultType(1,"项目【"+program.getProgramname()+"】初审不通过",200);
        }
        return new ResultType(0,"项目【"+program.getProgramname()+"】初审发生错误",200);
    }

    @PutMapping("/passsecondreview/{Level}")
    public ResultType passsecondReview(@RequestBody Program program,@PathVariable String Level){
        if(program.getApprovalStatus()==1){
            if(programService.passSecondReview(program.getProgramNumber(),Level)>0){
                return new ResultType(1,"项目【"+program.getProgramname()+"】二审通过",200);
            } else {
                return new ResultType(0,"项目【"+program.getProgramname()+"】二审发生错误",200);
            }
        }
        return new ResultType(0,"项目【"+program.getProgramname()+"】不处于审核中状态",200);
    }

    @PutMapping("/denysecondreview")
    public ResultType denysecondReview(@RequestBody Program program){
        if(program.getApprovalStatus()==1){
            if(programService.denySecondReview(program.getProgramNumber())>0){
                return new ResultType(1,"项目【"+program.getProgramname()+"】二审不通过",200);
            } else {
                return new ResultType(0,"项目【"+program.getProgramname()+"】二审发生错误",200);
            }
        }
        return new ResultType(0,"项目【"+program.getProgramname()+"】不处于审核中状态",200);
    }
}
